package com.jkdroid.maya.helper;

import android.content.Context;
import android.content.SharedPreferences;
import android.widget.EditText;

import java.util.Arrays;
import java.util.List;

/**
 * 草稿管理的类,用于发帖等页面，防止应用在用户不知情情况下退出时可以保存编辑内容以便下次使用
 * 会通过EditText的id作为key在sp里面保存内容
 * Created by guanzhihao on 2015/9/9.
 */
public class DraftHelper {

    private static final String BASE_NAME = "draft_";
    private static final String KEY_TIME = "key_time";
    private Context mContext;
    private String mKey;
    private SharedPreferences mSP;
    private boolean isOverTime;
    private long mValidateTime = 0; //有效时间，默认为0则永远有效
    private List<EditText> mEditTexts;

    /**
     * key会生成draft_[key]的sp文件
     * 建议传入ApplicationContext
     * @param context
     * @param key
     */
    public DraftHelper(Context context, String key, long validateTime){
        if(context == null){
            throw new NullPointerException("context can not be null");
        }
        this.mContext = context;
        this.mKey = key;
        this.mValidateTime = validateTime;
        this. mSP = mContext.getSharedPreferences(BASE_NAME+key, Context.MODE_PRIVATE);
        if(validateTime == 0){
            isOverTime = false;
        }else{
            long lastTime = mSP.getLong(KEY_TIME, 0);
            isOverTime = (lastTime + validateTime < System.currentTimeMillis()) ? true : false;
        }
    }

    public DraftHelper(Context context, String key){
        this(context, key, 0);
    }

    public void setEditTexts(EditText... ets){
        if(mEditTexts != null){
            mEditTexts.clear();
        }
        try{
            mEditTexts = Arrays.asList(ets);
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    public void saveAll(){
        if(mEditTexts == null || mEditTexts.size() <= 0){
            return;
        }
        for(EditText et : mEditTexts){
            saveText(et);
        }
        refreshDeadline();
    }

    public void clearAll(){
        mSP.edit().clear().apply();
    }

    public String getText(EditText et, String defString){
        if(isOverTime || et == null){
            return defString;
        }
        return mSP.getString(et.getId()+"", defString);
    }

    private void saveText(EditText et){
        if(et == null){
            return;
        }
        String id = et.getId()+"";
        String content = et.getText().toString();
        mSP.edit().putString(id, content).apply();
//        refreshDeadline();
    }

    private void refreshDeadline(){
        mSP.edit().putLong(KEY_TIME, System.currentTimeMillis()).apply();
    }

    public void release() {
        //TODO
    }
}
